using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GomokuGame.AI;

namespace GomokuGame
{
    /// <summary>
    /// 游戏记录管理器
    /// </summary>
    public class GameRecordManager
    {
        /// <summary>
        /// 游戏记录目录
        /// </summary>
        private string recordsDirectory;
        
        /// <summary>
        /// 当前游戏记录
        /// </summary>
        private GameRecord currentRecord;
        
        /// <summary>
        /// 游戏开始时间
        /// </summary>
        private DateTime gameStartTime;
        
        /// <summary>
        /// 是否启用自动保存
        /// </summary>
        public bool AutoSaveEnabled { get; set; } = true;
        
        /// <summary>
        /// 最大保存记录数
        /// </summary>
        public int MaxRecords { get; set; } = 100;
        
        public GameRecordManager()
        {
            // 设置记录目录
            recordsDirectory = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                "GomokuGame",
                "Records"
            );
            
            // 确保目录存在
            Directory.CreateDirectory(recordsDirectory);
        }
        
        /// <summary>
        /// 开始新游戏记录
        /// </summary>
        public void StartNewGameRecord(GameMode gameMode, AIDifficulty? aiDifficulty = null, PieceType? aiPlayer = null)
        {
            currentRecord = new GameRecord();
            gameStartTime = DateTime.Now;
            
            // 设置游戏信息
            currentRecord.GameInfo.GameMode = gameMode;
            currentRecord.GameInfo.AIDifficulty = aiDifficulty;
            currentRecord.GameInfo.AIPlayer = aiPlayer;
            currentRecord.GameInfo.StartTime = gameStartTime;
            
            // 设置玩家名称
            switch (gameMode)
            {
                case GameMode.HumanVsHuman:
                    currentRecord.GameInfo.BlackPlayer = "玩家1";
                    currentRecord.GameInfo.WhitePlayer = "玩家2";
                    break;
                case GameMode.HumanVsAI:
                    if (aiPlayer == PieceType.Black)
                    {
                        currentRecord.GameInfo.BlackPlayer = $"AI ({GetDifficultyName(aiDifficulty ?? AIDifficulty.Beginner)})";
                        currentRecord.GameInfo.WhitePlayer = "玩家";
                    }
                    else
                    {
                        currentRecord.GameInfo.BlackPlayer = "玩家";
                        currentRecord.GameInfo.WhitePlayer = $"AI ({GetDifficultyName(aiDifficulty ?? AIDifficulty.Beginner)})";
                    }
                    break;
                case GameMode.AIVsAI:
                    currentRecord.GameInfo.BlackPlayer = $"AI黑 ({GetDifficultyName(aiDifficulty ?? AIDifficulty.Beginner)})";
                    currentRecord.GameInfo.WhitePlayer = $"AI白 ({GetDifficultyName(aiDifficulty ?? AIDifficulty.Beginner)})";
                    break;
            }
        }
        
        /// <summary>
        /// 记录移动
        /// </summary>
        public void RecordMove(int row, int col, PieceType pieceType)
        {
            if (currentRecord == null)
            {
                return;
            }
            
            var timestamp = DateTime.Now - gameStartTime;
            currentRecord.AddMove(row, col, pieceType, timestamp);
        }
        
        /// <summary>
        /// 结束游戏记录
        /// </summary>
        public void EndGameRecord(PieceType winner, string winReason = "", bool isDraw = false)
        {
            if (currentRecord == null)
            {
                return;
            }
            
            currentRecord.GameInfo.EndTime = DateTime.Now;
            currentRecord.Result.Winner = winner;
            currentRecord.Result.WinReason = winReason;
            currentRecord.Result.IsDraw = isDraw;
            currentRecord.Result.TotalMoves = currentRecord.Moves.Count;
            currentRecord.Result.Duration = currentRecord.GameInfo.EndTime - currentRecord.GameInfo.StartTime;
            
            // 自动保存
            if (AutoSaveEnabled)
            {
                AutoSaveGameRecord();
            }
        }
        
        /// <summary>
        /// 手动保存当前游戏记录
        /// </summary>
        public string SaveCurrentGameRecord(string fileName = null)
        {
            if (currentRecord == null)
            {
                throw new InvalidOperationException("没有可保存的游戏记录");
            }
            
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = GenerateFileName();
            }
            
            string filePath = Path.Combine(recordsDirectory, fileName);
            currentRecord.SaveToXml(filePath);
            
            return filePath;
        }
        
        /// <summary>
        /// 自动保存游戏记录
        /// </summary>
        private void AutoSaveGameRecord()
        {
            try
            {
                string fileName = GenerateFileName();
                string filePath = Path.Combine(recordsDirectory, fileName);
                currentRecord.SaveToXml(filePath);
                
                // 清理旧记录
                CleanupOldRecords();
            }
            catch (Exception ex)
            {
                // 记录错误但不抛出异常
                System.Diagnostics.Debug.WriteLine($"自动保存游戏记录失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 加载游戏记录
        /// </summary>
        public GameRecord LoadGameRecord(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException($"游戏记录文件不存在: {filePath}");
            }
            
            return GameRecord.LoadFromXml(filePath);
        }
        
        /// <summary>
        /// 获取所有游戏记录文件
        /// </summary>
        public List<GameRecordInfo> GetAllGameRecords()
        {
            var records = new List<GameRecordInfo>();
            
            try
            {
                var files = Directory.GetFiles(recordsDirectory, "*.xml")
                    .OrderByDescending(f => File.GetLastWriteTime(f))
                    .Take(MaxRecords);
                
                foreach (var file in files)
                {
                    try
                    {
                        var record = LoadGameRecord(file);
                        records.Add(new GameRecordInfo
                        {
                            FilePath = file,
                            FileName = Path.GetFileName(file),
                            GameInfo = record.GameInfo,
                            Result = record.Result,
                            MoveCount = record.Moves.Count,
                            LastModified = File.GetLastWriteTime(file)
                        });
                    }
                    catch (Exception ex)
                    {
                        // 跳过损坏的文件
                        System.Diagnostics.Debug.WriteLine($"加载游戏记录失败 {file}: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取游戏记录列表失败: {ex.Message}");
            }
            
            return records;
        }
        
        /// <summary>
        /// 删除游戏记录
        /// </summary>
        public bool DeleteGameRecord(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    return true;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"删除游戏记录失败: {ex.Message}");
            }
            
            return false;
        }
        
        /// <summary>
        /// 导出为SGF格式
        /// </summary>
        public string ExportToSGF(string filePath = null)
        {
            if (currentRecord == null)
            {
                throw new InvalidOperationException("没有可导出的游戏记录");
            }
            
            string sgfContent = currentRecord.ExportToSGF();
            
            if (!string.IsNullOrEmpty(filePath))
            {
                File.WriteAllText(filePath, sgfContent, System.Text.Encoding.UTF8);
            }
            
            return sgfContent;
        }
        
        /// <summary>
        /// 生成文件名
        /// </summary>
        private string GenerateFileName()
        {
            string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            string mode = currentRecord.GameInfo.GameMode.ToString();
            string result = "";
            
            if (currentRecord.Result.IsDraw)
            {
                result = "Draw";
            }
            else if (currentRecord.Result.Winner != PieceType.Empty)
            {
                result = currentRecord.Result.Winner == PieceType.Black ? "BlackWin" : "WhiteWin";
            }
            
            return $"Gomoku_{timestamp}_{mode}_{result}.xml";
        }
        
        /// <summary>
        /// 清理旧记录
        /// </summary>
        private void CleanupOldRecords()
        {
            try
            {
                var files = Directory.GetFiles(recordsDirectory, "*.xml")
                    .OrderByDescending(f => File.GetLastWriteTime(f))
                    .Skip(MaxRecords);
                
                foreach (var file in files)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"删除旧记录失败 {file}: {ex.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"清理旧记录失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 获取难度名称
        /// </summary>
        private string GetDifficultyName(AIDifficulty difficulty)
        {
            switch (difficulty)
            {
                case AIDifficulty.Beginner: return "初级";
                case AIDifficulty.Intermediate: return "中级";
                case AIDifficulty.Advanced: return "高级";
                case AIDifficulty.Expert: return "专家";
                default: return "未知";
            }
        }
        
        /// <summary>
        /// 获取记录目录
        /// </summary>
        public string GetRecordsDirectory()
        {
            return recordsDirectory;
        }
        
        /// <summary>
        /// 获取当前游戏记录
        /// </summary>
        public GameRecord GetCurrentRecord()
        {
            return currentRecord;
        }
    }
    
    /// <summary>
    /// 游戏记录信息
    /// </summary>
    public class GameRecordInfo
    {
        public string FilePath { get; set; }
        public string FileName { get; set; }
        public GameInfo GameInfo { get; set; }
        public GameResult Result { get; set; }
        public int MoveCount { get; set; }
        public DateTime LastModified { get; set; }
    }
} 